package orchestration.xml;

import orchestration.android.parcelable.ParcelableAnnotation;
import orchestration.businessprocess.model.BPAnnotation;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
 * Factory to create BPAnnotations reading an XMLFile
 * @author <a href="mailto:car.ferrarini@gmail.com">Carlo Ferrarini</a>
 *
 */
public class BPAnnotationXmlFactory {
	
	/**
	 * 
	 * @param node an eAnnotation xml node
	 * @return the BPAnnotation described by this node
	 * @throws UnexpectedNodeException if called on a wrong node or if the annotation details don't respect the expected format
	 */
	public static BPAnnotation parseAnnotation(Node node) throws UnexpectedNodeException{
		if(!node.getNodeName().equals("eAnnotations"))
			throw new UnexpectedNodeException("This node does not contains an annotation");
		String id=node.getAttributes().getNamedItem("xmi:id").getNodeValue();
		String source=node.getAttributes().getNamedItem("source").getNodeValue();
		BPAnnotation result= new ParcelableAnnotation(id, source);
		NodeList childNodes = node.getChildNodes();
		for(int i=0; i<childNodes.getLength();i++){
			Node child= childNodes.item(i);
			if(child.getNodeName().equals("details")){
				NamedNodeMap attrs = child.getAttributes();
				if(!attrs.getNamedItem("xmi:type").getNodeValue().equals("ecore:EStringToStringMapEntry"))
					throw new UnexpectedNodeException("Only EStringToStringMapEntry details are supported!");
				String key= attrs.getNamedItem("key").getNodeValue();
				String value= attrs.getNamedItem("value").getNodeValue();
				result.putDetail(key, value);
			}
		}
		return result;
	}
}
